package com.mijie.homi.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.lucene.BigramAnalyzer;

import com.mijie.core.ApplicationProperties;
import com.mijie.core.StringFilter;
import com.mijie.homi.common.domain.SearchResult;
import com.mijie.util.Helper;
import com.mijie.util.HttpUtil;
import com.mijie.util.MailUtil;

public class ServerHelper {

	public static String API_IP = ApplicationProperties.get("server.domain")+":8282";
	public static String REQUEST_ATTR_USERID = "userId";
	public static String REQUEST_HEAD_ATTR_CHANNEL = "channel";
	private static Logger logger = Logger.getLogger(ServerHelper.class);
	private static  Analyzer bigramAnalyzer = new BigramAnalyzer();
	
	
	public static void logDeviceActive(String ip,String deviceId){
		logger.info("#/"+ip+"/terminal/active/"+deviceId);
	}
	
	public static boolean isLocalServer(){
		String isLocalServer = ApplicationProperties.get("isLocalServer");
		if(isLocalServer!=null && isLocalServer.equals("true")){
			return true;
		}
		return false;
	}
	
	public static boolean isInternalUser(int userId){
		if(userId<=100000 || userId==409005 || userId==5186038 
		  || userId==686716 || userId==465206 || userId==442497 
		  || userId==231202 || userId==1039471 || userId==397698 ) return true;
		return false;
	}
	
	public static SearchResult searchForList(String url){
		String content = null;
		try {
			content = HttpUtil.request(url, "GET", "UTF-8", null);
			JSONObject json = JSONObject.fromObject(content);
			return (SearchResult) JSONObject.toBean(json, SearchResult.class);
		} catch (Exception e) {
			logger.error("url:"+url+",content:"+content+"###");
			logger.error(e.getMessage(), e);
		}
		return null;
	}
	
	public static String getBigramToken(String str) {
		StringReader reader = new StringReader(str); 
	    StringBuilder sb = new StringBuilder();
	    TokenStream ts = null;
		try {
			ts = bigramAnalyzer.tokenStream(str, reader);
			ts.reset();
			CharTermAttribute termAtt = ts.getAttribute(CharTermAttribute.class);
			while (ts.incrementToken()){
				if(termAtt.length()>=2)
					sb.append(termAtt.toString()+" ");
			 }
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(ts!=null)
				try {
					ts.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return sb.toString();
	}
	
	public static Integer getUserId(HttpServletRequest request){
		return (Integer) request.getAttribute(REQUEST_ATTR_USERID);
	}
	
	public static Integer getChannel(HttpServletRequest request){
		String value =  request.getHeader(REQUEST_HEAD_ATTR_CHANNEL);
		if(value==null) return null;
		value = value.trim();
		if(value.isEmpty() || !Helper.isInt(value)) return null;
		return Integer.parseInt(value.trim());
	}
	
	public static String filterSensitiveWord(String src){
		return StringFilter.getInstanct().filter(src);
	}
	
	public static boolean containsDisabledWord(String src){
		return StringFilter.getInstanct().containsDisabledWord(src);
	}
	
	public static boolean sendMail(String sendTo,String subject,String content){
		MailUtil mail = new MailUtil();
		mail.setHost("smtp.51homi.net");  
		mail.setUserName("homing@51homi.net");  
		mail.setSenderName("哈米官方");
		mail.setPassWord("IAMmijie168");  
		mail.setTo(sendTo);  
		mail.setFrom("homing@51homi.net");  
		mail.setSubject(subject);  
		mail.setContent(content); 
		return mail.sendMail();
	}
	
	public static void reExportSensitiveWordFromDB(File file){
		int counter = 0;
		Connection conn = ServerHelper.getConnection();
		Statement stmt = null;
		ResultSet rs = null;
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		String delimiter = ",";
		String boundary = "\r\n";
		try{
			fos = new FileOutputStream(file);
			osw = new OutputStreamWriter(fos,"UTF-8");
			bw = new BufferedWriter(osw);
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT word,substitute FROM sensitiveWord");
			String substitude = null;
			while(rs.next()){
				substitude = rs.getString("substitute");
				bw.write(rs.getString("word"));
				bw.write(delimiter);
				bw.write(substitude);
				bw.write(delimiter);
				bw.write(String.valueOf(substitude.length()));
				bw.write(boundary);
				counter++;
			}
		}catch(Exception e){
			logger.error(e.getMessage(), e);
		}finally{
			try{
				if(bw!=null) bw.close();
				if(osw!=null) osw.close();
				if(fos!=null) fos.close();
				if(rs!=null) rs.close();
				if(stmt!=null) stmt.close();
				if(conn!=null) conn.close();
			}catch(Exception e){
				
			}
			logger.info("####export "+counter+" sensitive word from DB.");
		}
	}
	
	public static Connection getConnection() {
	   Connection conn=null;
	   try{
		   conn = DriverManager.getConnection("proxool.maindb");
	   } catch (SQLException e) {
		   e.printStackTrace();
	   }
	   return conn;
	}
	 
}
